package com.kpx.app.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kpx.app.R;
import com.kpx.app.activity.ActivityCertification;
import com.kpx.app.activity.ActivityCooperation;
import com.kpx.app.activity.ActivityMyPhotosNew;
import com.kpx.app.activity.ActivityMySuggestions;
import com.kpx.app.activity.ActivityMyTGList;
import com.kpx.app.activity.ActivityMyWallet;
import com.kpx.app.activity.ActivityOrderChoiceAddress;
import com.kpx.app.activity.ActivityOrderList;
import com.kpx.app.activity.ActivityOrderListByStatus;
import com.kpx.app.activity.ActivityPriseListNew;
import com.kpx.app.activity.ActivitySetting;
import com.kpx.app.activity.ActivityTobeSeller;
import com.kpx.app.activity.ActivityUploadManager;
import com.kpx.app.activity.ActivityUserInfo;
import com.kpx.app.activity.ActivityWebShow;
import com.kpx.app.activity.ActivityWithdrawals;
import com.kpx.app.adapter.MineFuncAdapter;
import com.kpx.app.base.FragmentBase;
import com.kpx.app.bean.ContactInfoBean;
import com.kpx.app.bean.LoginUser;
import com.kpx.app.bean.MineFuncBean;
import com.kpx.app.bean.OrderBean;
import com.kpx.app.bean.OrderCountBean;
import com.kpx.app.bean.Wallet;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.ImageLoader;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.OperationJson;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.wigdet.AutoSizeGridView;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/12/20.
 * 我的
 */
public class FragmentMine extends FragmentBase {
    @BindView(R.id.img_user_icon)
    ImageView imgUserIcon;
    @BindView(R.id.txt_user_name)
    TextView txtUserName;
    @BindView(R.id.txt_user_point)
    TextView txtUserPoint;
    @BindView(R.id.img_setting)
    TextView imgSetting;
    @BindView(R.id.txt_vip_center)
    TextView txtVipCenter;
    @BindView(R.id.txt_orders)
    TextView txtOrders;
    @BindView(R.id.txt_order_waitting_pay)
    TextView txtOrderWaittingPay;
    @BindView(R.id.txt_order_waitting_send)
    TextView txtOrderWaittingSend;
    @BindView(R.id.txt_order_waitting_upload)
    TextView txtOrderWaittingUpload;
    @BindView(R.id.txt_order_waitting_check)
    TextView txtOrderWaittingCheck;
    @BindView(R.id.txt_order_waitting_back)
    TextView txtOrderWaittingBack;
    @BindView(R.id.asgv_mine_fun)
    AutoSizeGridView asgvMineFun;
    @BindView(R.id.txt_price_canuse)
    TextView txtPriceCanuse;
    @BindView(R.id.txt_price_dongjie)
    TextView txtPriceDongjie;
    @BindView(R.id.txt_mine_point)
    TextView txtMinePoint;
    @BindView(R.id.txt_mine_tixian)
    TextView txtMineTixian;
    @BindView(R.id.ll_price_canuse)
    LinearLayout llPriceCanuse;
    @BindView(R.id.ll_price_dongjie)
    LinearLayout llPriceDongjie;
    @BindView(R.id.ll_mine_point)
    LinearLayout llMinePoint;
    @BindView(R.id.txt_count1)
    TextView txtCount1;
    @BindView(R.id.txt_count2)
    TextView txtCount2;
    @BindView(R.id.txt_count3)
    TextView txtCount3;
    @BindView(R.id.txt_count4)
    TextView txtCount4;
    @BindView(R.id.txt_count5)
    TextView txtCount5;

    private List<MineFuncBean> mineFuncBeens = new ArrayList<>();
    private int[] icons = {
            R.drawable.mine_func_certification,
            R.drawable.mine_func_my_tg,
            R.drawable.mine_func_my_pic,
            R.drawable.mine_func_my_prise,

            R.drawable.mine_func2_my_goods, R.drawable.mine_func2_upload,
            R.drawable.mine_func2_my_address, R.drawable.mine_func2_yijian,

            R.drawable.mine_func3_is_shop, R.drawable.mine_func3_to_hezuo,
            R.drawable.mine_func3_guanfang, R.drawable.mine_func3_kefu
    };

    @Override
    public int setLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        registOnclick();
        return rootView;
    }

    public void loadData() {
        LoginUser loginUser = UserInfoUtils.getCachedLoginUser();
        ImageLoader.loadCircle(getActivity(), loginUser.getUSER().getHeadImg(), imgUserIcon, R.drawable.default_head_img2);
        txtUserName.setText(loginUser.getUSER().getNickName());
        UserInfoUtils.getMyWallet(getActivity(), new UserInfoUtils.OnGetMyWalletBackListener() {
            @Override
            public void back(Wallet aBeans) {
                txtUserPoint.setText("积分：" + (int) aBeans.getScoreAmount() + "");
                txtMinePoint.setText(aBeans.getIntegralAmount() + "");
                txtPriceCanuse.setText(aBeans.getCashAmount() + "");
                txtPriceDongjie.setText(aBeans.getBlockedAmount() + "");
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserInfoUtils.isUserLogin()) {
            refreshData();

        }
    }

    public void refreshData() {
        loadData();
        getOrderCountShow();
    }

    public void getOrderCountShow() {
        MyHashMap map = new MyHashMap();
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    if (result.getData() != null) {
                        if (null != result.getData()) {
                            clearStatus(txtCount1);
                            clearStatus(txtCount2);
                            clearStatus(txtCount3);
                            clearStatus(txtCount4);
                            clearStatus(txtCount5);
                            ArrayList<OrderCountBean> counts = (ArrayList<OrderCountBean>) result.getData();
                            for (int i = 0; i < counts.size(); i++) {
                                switch (counts.get(i).getOrderStatus()) {
                                    case OrderBean.ORDER_STATUS_WAITTING_PAY:
                                        txtCount1.setText(counts.get(i).getNum() + "");
                                        txtCount1.setVisibility(counts.get(i).getNum() > 0 ? View.VISIBLE : View.GONE);
                                        break;
                                    case OrderBean.ORDER_STATUS_WAITTING_SEND:
                                        txtCount2.setText(counts.get(i).getNum() + "");
                                        txtCount2.setVisibility(counts.get(i).getNum() > 0 ? View.VISIBLE : View.GONE);
                                        break;
                                    case OrderBean.ORDER_STATUS_WAITTING_UPLOAD:
                                        txtCount3.setText(counts.get(i).getNum() + "");
                                        txtCount3.setVisibility(counts.get(i).getNum() > 0 ? View.VISIBLE : View.GONE);
                                        break;
                                    case OrderBean.ORDER_STATUS_WATTING_CHECK:
                                        txtCount4.setText(counts.get(i).getNum() + "");
                                        txtCount4.setVisibility(counts.get(i).getNum() > 0 ? View.VISIBLE : View.GONE);
                                        break;
                                    case OrderBean.ORDER_STATUS_WATTING_BACK:
                                        txtCount5.setText(counts.get(i).getNum() + "");
                                        txtCount5.setVisibility(counts.get(i).getNum() > 0 ? View.VISIBLE : View.GONE);
                                        break;
                                }
                            }
                        }
                    }
                } else {
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
            }

        }, OrderCountBean.class, HttpDataRequest.TYPE_LIST).POST(HttpDataReqUrl.URL_POST_GET_ORDER_STATUS_COUNT, true, map);
    }

    private void clearStatus(TextView txt) {
        txt.setText("0");
        txt.setVisibility(View.GONE);
    }

    private void registOnclick() {
        MineFuncAdapter adapter = new MineFuncAdapter(getActivity(), mineFuncBeens, R.layout.item_func_mine);
        setFuncData(adapter);
        asgvMineFun.setAdapter(adapter);
        asgvMineFun.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                toGo(mineFuncBeens.get(position).getName());
            }
        });
        txtVipCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toVip();
            }
        });
    }

    private void toVip() {
        showLoadingDialog(getActivity());
        MyHashMap map = new MyHashMap();
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog(getActivity());
                if (result.getCode() == 0) {
                    if (result.getData() != null) {
                        String str = null;
                        if (null != result.getData()) {
                            str = JSON.toJSONString(result.getData());
                            try {
                                HashMap<String, String> map = OperationJson.resolvingJsonObject(str);
                                if (TextUtils.isEmpty(map.get("centerUrl"))) {
                                    ToastUtil.getInstance().showToast(getActivity(), "暂未开放，敬请期待");
                                    return;
                                }
                                ActivityWebShow.type = 1;
                                ActivityWebShow.url = map.get("centerUrl") + "?dmid=" + UserInfoUtils.getCachedLoginUser().getUSER().getDmId();
                                IntentUtil.gotoActivity(getActivity(), ActivityWebShow.class);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    ToastUtil.getInstance().showToast(getActivity(), result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog(getActivity());
                ToastUtil.getInstance().showToast(getActivity(), error);
            }

        }, null, null).POST(HttpDataReqUrl.URL_POST_VIP_CENTER, true, map);
    }

    private void toGo(String name) {
        if (name.endsWith("资料认证")) {
            IntentUtil.gotoActivity(getActivity(), ActivityCertification.class);
        } else if (name.endsWith("我的推广")) {
            IntentUtil.gotoActivity(getActivity(), ActivityMyTGList.class);
        } else if (name.endsWith("我的图片")) {
            IntentUtil.gotoActivity(getActivity(), ActivityMyPhotosNew.class);
//            IntentUtil.gotoActivity(getActivity(), ActivityMyPhotos.class);
        } else if (name.endsWith("我的评价")) {
            IntentUtil.gotoActivity(getActivity(), ActivityPriseListNew.class);
        } else if (name.endsWith("我的实物")) {
            ActivityOrderListByStatus.orderType = OrderBean.ORDER_STATUS_MY_GOODS;
            IntentUtil.gotoActivity(getActivity(), ActivityOrderListByStatus.class);
        } else if (name.endsWith("上传进度")) {
            IntentUtil.gotoActivity(getActivity(), ActivityUploadManager.class);
        } else if (name.endsWith("我是商家")) {
            IntentUtil.gotoActivity(getActivity(), ActivityTobeSeller.class);
        } else if (name.endsWith("我要合作")) {
            IntentUtil.gotoActivity(getActivity(), ActivityCooperation.class);
        } else if (name.endsWith("意见反馈")) {
            IntentUtil.gotoActivity(getActivity(), ActivityMySuggestions.class);
        } else if (name.endsWith("收货地址")) {
            IntentUtil.gotoActivity(getActivity(), ActivityOrderChoiceAddress.class);
        } else if (name.endsWith("官方号")) {
//            ToastUtil.getInstance().showToast(getActivity(), "即将开放");
//            UserInfoUtils.getSellerInfo(getActivity(), new UserInfoUtils.OnGetSellerInfoBackListener() {
//                @Override
//                public void back(ContactInfoBean b) {
//                    if (b != null) {
//                        UIUtils.goQQChat(b.getQQ());
//                    }else{
//                        ToastUtil.getInstance().showToast(getActivity(), "即将开放");
//                    }
//                }
//            });
            getOFFICE();
        } else if (name.endsWith("我的客服")) {
            UserInfoUtils.getSellerInfo(getActivity(), new UserInfoUtils.OnGetSellerInfoBackListener() {
                @Override
                public void back(ContactInfoBean b) {
                    if (b != null) {
                        UIUtils.goQQChat(b.getQQ());
                    } else {
                        ToastUtil.getInstance().showToast(getActivity(), "即将开放");
                    }
                }
            });
        }
    }

    private void getOFFICE() {
        showLoadingDialog(getActivity());
        MyHashMap map = new MyHashMap();
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog(getActivity());
                if (result.getCode() == 0) {
                    if (result.getData() != null) {
                        String str = null;
                        if (null != result.getData()) {
                            str = JSON.toJSONString(result.getData());
                            try {
                                HashMap<String, String> map = OperationJson.resolvingJsonObject(str);
                                if (TextUtils.isEmpty(map.get("html"))) {
                                    ToastUtil.getInstance().showToast(getActivity(), "暂未开放，敬请期待");
                                    return;
                                }
                                ActivityWebShow.type = 2;
                                ActivityWebShow.title = "官方号";
                                ActivityWebShow.url = map.get("html");
                                IntentUtil.gotoActivity(getActivity(), ActivityWebShow.class);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    ToastUtil.getInstance().showToast(getActivity(), result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog(getActivity());
                ToastUtil.getInstance().showToast(getActivity(), error);
            }

        }, null, null).POST(HttpDataReqUrl.URL_POST_GET_OFFICE, true, map);
    }

    private void setFuncData(MineFuncAdapter adapter) {
        String[] funcs = getActivity().getResources().getStringArray(R.array.func_names);
        for (int i = 0; i < funcs.length; i++) {
            MineFuncBean b = new MineFuncBean();
            b.setName(funcs[i]);
            b.setResId(icons[i]);
            mineFuncBeens.add(b);
        }
        adapter.setData(mineFuncBeens);
    }

    @OnClick({R.id.img_user_icon, R.id.img_setting, R.id.txt_vip_center, R.id.txt_orders, R.id.txt_order_waitting_pay, R.id.txt_order_waitting_send, R.id.txt_order_waitting_upload, R.id.txt_order_waitting_check, R.id.txt_order_waitting_back, R.id.ll_price_canuse, R.id.ll_price_dongjie, R.id.ll_mine_point, R.id.txt_mine_tixian})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_user_icon://用户头像
                IntentUtil.gotoActivity(getActivity(), ActivityUserInfo.class);
                break;
            case R.id.img_setting://设置
                IntentUtil.gotoActivity(getActivity(), ActivitySetting.class);
                break;
            case R.id.txt_vip_center://会员中心
                IntentUtil.gotoActivity(getActivity(), ActivityUserInfo.class);
                break;
            case R.id.txt_orders://我的订单
                IntentUtil.gotoActivity(getActivity(), ActivityOrderList.class);
                break;
            case R.id.txt_order_waitting_pay://待支付
                Bundle bundle = new Bundle();
                bundle.putString("order_status", OrderBean.ORDER_STATUS_WAITTING_PAY + "");
                IntentUtil.gotoActivity(getActivity(), ActivityOrderList.class, bundle);
                break;
            case R.id.txt_order_waitting_send://待发货
                bundle = new Bundle();
                bundle.putString("order_status", OrderBean.ORDER_STATUS_WAITTING_SEND + "");
                IntentUtil.gotoActivity(getActivity(), ActivityOrderList.class, bundle);
                break;
            case R.id.txt_order_waitting_upload://待上传
                bundle = new Bundle();
                bundle.putString("order_status", OrderBean.ORDER_STATUS_WAITTING_UPLOAD + "");
                IntentUtil.gotoActivity(getActivity(), ActivityOrderList.class, bundle);
                break;
            case R.id.txt_order_waitting_check://待审核
                bundle = new Bundle();
                bundle.putString("order_status", OrderBean.ORDER_STATUS_WATTING_CHECK + "");
                IntentUtil.gotoActivity(getActivity(), ActivityOrderList.class, bundle);
                break;
            case R.id.txt_order_waitting_back://待退回
                bundle = new Bundle();
                bundle.putString("order_status", OrderBean.ORDER_STATUS_WATTING_BACK + "");
                IntentUtil.gotoActivity(getActivity(), ActivityOrderList.class, bundle);
                break;
            case R.id.txt_mine_tixian://提现
                IntentUtil.gotoActivity(getActivity(), ActivityWithdrawals.class);
                break;
            case R.id.ll_price_canuse:
            case R.id.ll_price_dongjie:
            case R.id.ll_mine_point:
                IntentUtil.gotoActivity(getActivity(), ActivityMyWallet.class);
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
